import { defineStore } from 'pinia';
import axios from 'axios';

export const useDownloadStore = defineStore('downloadStore', {
  state: () => ({
    loading: false,
  }),
  actions: {
    async downloadFile(fileName: string, repoLink?: string): Promise<void> {
      if (!fileName) {
        alert('请输入文件名');
        return;
      }

      this.loading = true;

      try {
        const downloadUrl = repoLink
          ? `http://127.0.0.1:5000/downloadRepo?repo=${repoLink}`
          : 'http://127.0.0.1:5000/download';

        console.log('Downloading from:', downloadUrl);
        
        const response = await axios.get(downloadUrl, {
          responseType: 'blob', // 返回Blob类型
        });

        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;

        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href); // 下载完成后释放对象 URL
        document.body.removeChild(link); // 移除链接

      } catch (error) {
        console.error('Download failed:', error);
        alert('下载失败，请重试。');
      } finally {
        this.loading = false;
      }
    },
  },
});